package com.lifeng.mynetty.client.handler;


import com.lifeng.mynetty.constants.MyNettyContants;
import com.lifeng.mynetty.response.Cache;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created by lifeng
 * 2017/9/4 16:09
 */
public class HttpPostClientHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(HttpPostClientHandler.class);
    private String charset = "utf-8";

    public HttpPostClientHandler() {
    }
    public HttpPostClientHandler(String charset){
        this.charset = charset;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpResponse)
        {
            HttpResponse response = (HttpResponse) msg;
            System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
        }
        if(msg instanceof HttpContent)
        {
            HttpContent content = (HttpContent)msg;
            ByteBuf buf = content.content();
            String att = (String)ctx.channel().attr(AttributeKey.valueOf(MyNettyContants.MSG_KEY)).get();
            if(att != null && !"".equals(att)){
                logger.debug("附件属性:"+att);
                Cache.getInstance().getCallback(att).callback(buf.toString(Charset.forName(charset)));
            }
            logger.info("收到服务端响应:"+buf.toString(Charset.forName(charset)));
        }

    }
}
